package uk.org.landeg.euler.problems.lib;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import uk.org.landeg.euler.problems.framework.AbstractProblem;

public abstract class MaxPathTriangle extends AbstractProblem {

	abstract protected String getFileName ();



	int[][] data;
	@Override
	public Object solve() {
		try {
			parseData();

			int rowId = data.length - 2;
			int num = 0;
			while (rowId >= 0) {
				for (num = 0 ; num < data[rowId].length ; num++) {
					data[rowId][num] += Math.max(data[rowId+1][num], data[rowId+1][num+1]);
				}
				rowId--;
			}
			return data[0][0];
		} catch (Exception e) {
			return e;
		}
	}
	
	private ArrayList<ArrayList<Integer>>parseData () throws NumberFormatException, IOException {
		ArrayList<ArrayList<Integer>> listdata = new ArrayList<ArrayList<Integer>>();
		ArrayList<Integer> lineData;
		String line = null;
		BufferedReader reader = new BufferedReader (new FileReader(getFileName()));
		Pattern p = Pattern.compile("\\d{2}");
		Matcher m;
		while ((line = reader.readLine()) != null) {
			lineData = new ArrayList<Integer>();
			m = p.matcher(line);
			while (m.find()) {
				lineData.add(Integer.parseInt(m.group()));
			}
			listdata.add(lineData);
			System.out.println("Read line\t" + lineData.toString());
		}
		data = new int[listdata.size()][];
		for (int rowId = 0 ; rowId < listdata.size() ; rowId++) {
			data[rowId] = new int[listdata.get(rowId).size()];
			for (int id = 0 ;id < listdata.get(rowId).size() ; id++) {
				data[rowId][id] = listdata.get(rowId).get(id);
			}
		}
		return listdata;
	}
}
